import { isLogin } from '@/stores/token'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // {
    //   path: '/',
    //   name: 'home',
    //   component: HomeView,
    // },
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue'),
    // },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/common/LoginPage.vue'),
    },
    // 后台管理
    {
      path: '/backend',
      name: 'backend',
      component: () => import('../views/backend/BackendLayout.vue'),
      redirect: '/backend/blog',
      children: [
        {
          path: 'blog',
          name: 'blog_management',
          redirect: '/backend/blog/list',
          meta: {
            lable: '文章管理',
          },
          children: [
            {
              path: 'list',
              name: 'backend_blog_list',
              component: () => import('../views/backend/blog/ListPage.vue'),
              meta: {
                lable: '文章列表',
              },
            },
            {
              path: 'edit',
              name: 'backend_blog_edit',
              component: () => import('../views/backend/blog/EditPage.vue'),
              meta: {
                lable: '文章编辑',
              },
            },
            {
              path: 'tag_list',
              name: 'backend_tag_list',
              component: () => import('../views/backend/tag/ListPage.vue'),
            },
          ],
        },
        {
          path: 'comment',
          name: 'comment_management',
          children: [
            {
              path: 'list',
              name: 'backend_comment_list',
              component: () => import('../views/backend/blog/ListPage.vue'),
            },
          ],
        },
      ],
    },
    {
      path: '/frontend',
      name: 'frontend',
      redirect: '/frontend/blog_list',
      component: () => import('../views/frontend/FrontendLayout.vue'),
      children: [
        {
          path: 'blog_list',
          name: 'frontend_blog_list',
          component: () => import('../views/frontend/blog/ListPage.vue'),
        },
        {
          path: 'blog_detail',
          name: 'frontend_blog_detail',
          component: () => import('../views/frontend/blog/DetailPage.vue'),
        },
      ],
    },
  ],
})

router.beforeEach((to, from) => {
  const whiteList = ['login', 'frontend']
  if (!whiteList.includes(to.name)) {
    // 需要做权限判断
    if (isLogin()) {
      return true
    }
    // 返回跳转后的页面
    return { name: 'login' }
  }
})

export default router
